
package pers.kevin.fsm.utils;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class FileUtil {

	/**
	 * delete file or directory include all file in directory
	 * @param filePath
	 */
	public static void deleteFile(String filePath) {
		File file = new File(filePath);
		if(file.exists()) {
			if(file.isDirectory()) {
				for (File currentFile : file.listFiles()) {
					if(currentFile.isDirectory()) {
						deleteFile(currentFile.getPath());
						currentFile.delete();
					}else {
						currentFile.delete();
					}
				}
				file.delete();
			}else {
				file.delete();
			}
		}
		
	}
	
	/**
	 *  copy file from location to destination
	 * @param location
	 * @param destination
	 * @throws IOException
	 */
	public static void copyFile(String location,String destination) throws IOException {
		BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(location),1024);
		BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(destination),1024);
		int content = 0;
		while((content = bufferedInputStream.read()) != -1){
			bufferedOutputStream.write(content);
		}
		bufferedInputStream.close();
		bufferedOutputStream.close();
	}
	
	
	/**
	 * copy file or directory from location to destination ,and include all file in directory
	 * @param location
	 * @param destination
	 * @throws IOException
	 */
	public static void copy(String location,String destination) throws IOException {
		File file = new File(location);
		if(file.exists()) {
			if(file.isDirectory()) {
				//destination create a directory
				//save destination path
				String dirPath = destination + "\\" + file.getName();
				File dirFile = new File(dirPath);
				dirFile.mkdirs();
				for (File currentFile : file.listFiles()) {
					if(currentFile.isDirectory()) {
						copy(location + "\\" + currentFile.getName(),dirPath);
					}else {
						copyFile(location + "\\" + currentFile.getName(),dirPath + "\\" + currentFile.getName());
					}
				}
			
			}else {
				copyFile(location,destination);
			}
		}
	}
	
	/**
	 * list all files 
	 * @param dirPath
	 * @return 
	 */
	public static File[] listFilesInfo(String dirPath){
	    File file = new File(dirPath);
	    if(file.exists()){
	        if(file.isDirectory()){
	            return file.listFiles();
	        }
	    }
	    return null;
	}
}
